import re
import sys

def remove_image_attributes(file_path):
    """去除Markdown文件中图片的尺寸属性"""
    try:
        # 尝试不同的编码格式读取文件
        encodings = ['utf-8', 'gbk', 'utf-16', 'latin-1']
        content = None
        used_encoding = None
        
        for encoding in encodings:
            try:
                with open(file_path, 'r', encoding=encoding) as f:
                    content = f.read()
                used_encoding = encoding
                break
            except UnicodeDecodeError:
                continue
        
        if content is None:
            print(f"无法读取文件 {file_path}，尝试了所有编码格式")
            return False
        
        # 使用正则表达式去除图片尺寸属性
        # 匹配 {width="..." height="..."} 格式
        pattern = r'\{width="[^"]*"\s*height="[^"]*"\}'
        cleaned_content = re.sub(pattern, '', content)
        
        # 写回文件，使用检测到的编码格式
        with open(file_path, 'w', encoding=used_encoding) as f:
            f.write(cleaned_content)
        
        print(f"已成功去除 {file_path} 中的图片尺寸属性 (使用编码: {used_encoding})")
        return True
        
    except Exception as e:
        print(f"处理文件 {file_path} 时出错: {e}")
        return False

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("用法: python remove_image_attrs.py <markdown_file_path>")
        sys.exit(1)
    
    file_path = sys.argv[1]
    remove_image_attributes(file_path)